package com.sr.examination;

import android.support.multidex.MultiDexApplication;

import com.sr.examination.net.Net;
import com.sr.examination.user.Account;
import com.tl.commonlibrary.AppConfig;
import com.tl.commonlibrary.network.ErrorResponse;
import com.tl.commonlibrary.network.RequestListener;
import com.tl.commonlibrary.network.bean.base.BaseBean;
import com.tl.commonlibrary.storage.database.DBManager;
import com.tl.commonlibrary.ui.beans.User;
import com.tl.commonlibrary.ui.exception.CrashHandler;

import retrofit2.Call;

/**
 * Created by Administrator on 2017/6/5 0005.
 */

public class MyApplication extends MultiDexApplication {
    private static MyApplication myApplication;

    public static synchronized MyApplication get() {
        return myApplication;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        myApplication = this;
        AppConfig.setApplication(this);
        CrashHandler.get().init();
        DBManager.get().init(this, "sr_exam");
    }

    public void updateUserInfo(final OnUpdateUserInfoListener listener) {
        updateUserInfo(listener != null, listener);
    }

    public void updateUserInfo() {
        updateUserInfo(false, null);
    }

    public void updateUserInfo(final boolean hasEvent, final OnUpdateUserInfoListener listener) {
        if (Account.isNotLogged()) {
            return;
        }
        Net.getUserInfo(new RequestListener<BaseBean<User>>() {
            @Override
            public void onSuccess(Call<BaseBean<User>> call, BaseBean<User> response) {
                if (response.isSuccessful()) {
                    User user = Account.getUser();
                    if (user != null) {
                        response.data.setToken(user.getToken());
                        if (hasEvent) {
                            com.tl.commonlibrary.ui.user.Account.setUser(response.data);
                        } else {
                            com.tl.commonlibrary.ui.user.Account.setUserNoEvent(response.data);
                        }
                        if (listener != null) {
                            listener.onUpdateUserInfo(response.data);
                        }
                    }
                }
            }

            @Override
            public void onFailed(Call<BaseBean<User>> call, ErrorResponse errorResponse) {

            }
        });
    }

    public interface OnUpdateUserInfoListener {
        void onUpdateUserInfo(User user);
    }
}
